package ru.home.shoppinglist;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

public class AddClassificationActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_classification);
		long id = getIntent().getLongExtra("category_id", -1);
		if (id != -1) {
			DBHelper dbh = new DBHelper(this);
			SQLiteDatabase db = dbh.getWritableDatabase();
			Cursor cur = db.rawQuery(
					"select name,parentid from Classification where id=" + id,
					null);
			String name = null;
			while (cur.moveToNext()) {
				name = cur.getString(0);
			}
			dbh.close();
			((TextView) findViewById(R.id.edCatName)).setText(name);
			((TextView) findViewById(R.id.btApplyChanges)).setText("Save");
			((TextView) findViewById(R.id.btDeleteCategory))
					.setVisibility(TextView.VISIBLE);
		} else {
			TextView v = (TextView) findViewById(R.id.btApplyChanges);
			// v.setWidth(LayoutParams.MATCH_PARENT);
			LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,
					LayoutParams.WRAP_CONTENT);
			lp.addRule(RelativeLayout.BELOW, R.id.edCatName);
			v.setLayoutParams(lp);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.add_classification, menu);
		return true;
	}

	public void onAddRecordClick(View view) {
		EditText catName = (EditText) findViewById(R.id.edCatName);
		DBHelper dbh = new DBHelper(this);
		SQLiteDatabase db = dbh.getWritableDatabase();
		ContentValues cv = new ContentValues();
		cv.put("name", catName.getText().toString());
		long id = getIntent().getLongExtra("category_id", -1);
		if (id == -1) {
			db.insert("Classification", null, cv);
		} else {
			db.update("Classification", cv, "id=" + id, null);
		}
		db.close();
		dbh.close();
		finish();
	}

	public void onDeleteClick(View view) {		
		DBHelper dbh = new DBHelper(this);
		SQLiteDatabase db = dbh.getWritableDatabase();		
		long id = getIntent().getLongExtra("category_id", -1);
		if (id == -1) {		
		} else {
			db.delete("Classification", "id=" + id, null);
		}
		db.close();
		dbh.close();
		finish();
	}

	public void onCancelClick(View view) {

		finish();
	}

}
